import bcrypt from 'bcryptjs';
import crypto from 'crypto';
import jwt from 'jsonwebtoken';

// 生成随机盐值
export const generateSalt = (length = 32) => {
  return crypto.randomBytes(length / 2).toString('hex');
};

// 生成密码哈希
export const hashPassword = async (password, salt) => {
  // 使用bcrypt进行密码哈希
  return await bcrypt.hash(password + salt, 10);
};

// 验证密码
export const verifyPassword = async (password, salt, storedHash) => {
  // 生成输入密码的哈希并与存储的哈希比较
  const hashedInput = await bcrypt.hash(password + salt, 10);
  return hashedInput === storedHash;
};

// 或者使用bcrypt的verify方法（更推荐）
export const verifyPasswordBcrypt = async (password, storedHash) => {
  return await bcrypt.compare(password, storedHash);
};

// 生成JWT令牌
export const generateToken = (payload, expiresIn = process.env.JWT_EXPIRES_IN || '24h') => {
  return jwt.sign(payload, process.env.JWT_SECRET, { expiresIn });
};

// 生成随机字符串
export const generateRandomString = (length = 8) => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
};

// 生成患者匿名编号
export const generatePatientCode = () => {
  const prefix = 'P';
  const timestamp = Date.now().toString(36);
  const random = Math.random().toString(36).substring(2, 8);
  return `${prefix}${timestamp}${random}`.toUpperCase();
};